package com.hyfrogx.modules.zoom.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.param.Constants;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.validator.ValidatorUtils;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.sys.controller.AbstractController;
import com.hyfrogx.modules.zoom.entity.HyVipMeetConfig;
import com.hyfrogx.modules.zoom.entity.HyZoomReserve;
import com.hyfrogx.modules.zoom.entity.ZoomReservePrice;
import com.hyfrogx.modules.zoom.form.HyZoomReserveForm;
import com.hyfrogx.modules.zoom.param.ZoomPirce;
import com.hyfrogx.modules.zoom.service.HyZoomReserveService;
import com.hyfrogx.modules.zoom.service.ZoomReservePriceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：Li9527
 * @date ：Created in 2019-11-15 15:31
 * @description：${description}
 * @modified By：
 * @version: 1.0.0
 */
@RestController
@RequestMapping("/meetReserve")
@Api(value = "zoom预约管理controller", tags = {"后台--预约管理"})
public class ZoomReserveController extends AbstractController {

    @Autowired
    ZoomReservePriceService reservePriceService;

    @Autowired
    HyZoomReserveService zoomReserveService;

    @Autowired
    UserService userService;

    @Autowired
    HyPayRecordService payRecordService;

    /**
     * 获取预约会议室定价参数
     *
     * @param
     * @return
     * @throws MyException
     */
    @GetMapping("/getReservePriceList")
    @ApiOperation("获取预约会议室定价参数")
    public R getReservePrice() {
        try {
            List<ZoomReservePrice> list = reservePriceService.list();
            return R.ok().put("data", list);
        } catch (MyException e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 根据规模修改价格<批量修改>
     *
     * @param jsonStr
     * @throws MyException
     */
    @PostMapping("/updateReservePriceList")
    @ApiOperation("根据规模修改价格<批量修改>")
    public R updateList(String jsonStr) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(jsonStr);
            List<ZoomReservePrice> zoomReservePriceList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                ZoomReservePrice zoomReservePrice = jsonArray.getObject(i, ZoomReservePrice.class);
                zoomReservePriceList.add(zoomReservePrice);
            }
            Boolean flag = reservePriceService.saveOrUpdateBatch(zoomReservePriceList);
            if (flag) {
                return R.ok("修改成功");
            } else {
                return R.error("修改失败");
            }
        } catch (MyException e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 获取预约订单列表
     *
     * @param params
     * @return R
     */
    @GetMapping("/getByPage")
    @ApiOperation("获取预约订单列表")
    public R getVipZoomlist(@RequestParam Map<String, Object> params) {
        Page page = zoomReserveService.selectPageByConditions(new QueryExt(params));
        if (page.getRecords().size() > 0) {
            return R.ok().put("page", page);
        } else {
            return R.error("无数据");
        }
    }

    /**
     * 预约会议室
     *
     * @param
     * @return
     * @throws
     */
    @PostMapping("/create")
    @ApiOperation("预约会议室")
    public R createMeet(@RequestBody HyZoomReserveForm reserveForm) {
        try {
            ValidatorUtils.validateClientEntity(reserveForm);
            // 校验手机号是否为平台内手机号,获取主持会议者信息
            User usr = userService.getUserByPhone(reserveForm.getPhone());
            if (usr == null) {
                return R.error("请输入正确的客户端手机号");
            }
            // 当前五分钟以后的时间才可以
            Long timeMs = System.currentTimeMillis() + 60 * 5;
            if (reserveForm.getReserveTime() <= timeMs) {
                return R.error("请选择离当前时间五分钟后的时间,因为定时任务每五分钟执行一次绑定至会议室");
            }
            HyZoomReserve zoomReserve = new HyZoomReserve();
            Date d = new Date(reserveForm.getReserveTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println(sdf.format(d));
            zoomReserve.setUseDate(sdf.format(d));
            BeanUtils.copyProperties(reserveForm, zoomReserve);
            // 设置实际预约者用户id
            zoomReserve.setSysUid(getUserId());
            zoomReserve.setStatus(FrogConstant.Status.FLASE);
            zoomReserve.setCreateAt(new Date());
            // 设置会议室使用者用户id
            zoomReserve.setUid(usr.getUid());
            // 根据规模取得价格
            ZoomReservePrice zoomReservePrice = reservePriceService.getOne(new QueryWrapper<ZoomReservePrice>().eq(
                    "meetingcapacity", reserveForm.getMeetingCapacity()));
            if (zoomReservePrice == null) {
                return R.error("该规格会议室价格丢失");
            }
            zoomReserve.setNeedPay(zoomReservePrice.getPrice());
            zoomReserve.setTruePay(zoomReservePrice.getPrice());
            // 校验当天该类会议室是否被预约满
            int code = zoomReserveService.jugeHaveMeetZoom(zoomReserve.getUseDate(), zoomReserve.getMeetingCapacity());
            if (code == -1) {
                return R.error("该日该规模会议室已被预约完,请试试其他规模会议室");
            } else {
                zoomReserve.setZid(code);
            }
            // 已经可预约,对该用户进行收钱,如果钱不够,返回蛙豆方面消息
            userService.reduce(usr.getUid(), zoomReservePrice.getPrice());
            // 生成订单
            HyPayRecord payRecord = new HyPayRecord();
            payRecord.setCreatedate(new Date());
            payRecord.setTotal(zoomReserve.getTruePay());
            payRecord.setMoney(0);
            payRecord.setNum(0);
            payRecord.setType(PayType.zoom_reserve.getCode());
            payRecord.setYid(0l);
            // 预约者id
            payRecord.setUid(usr.getUid());
            // 会议室id
            payRecord.setSid(code);
            payRecordService.save(payRecord);
            Boolean result = zoomReserveService.save(zoomReserve);
            if (result) {
                return R.ok("预约成功");
            } else {
                return R.error("预约失败");
            }
        } catch (MyException e) {
            return R.error(e.getMsg());
        }
    }
}
